package User

import (
	Hashstr "beego_base_demo/Hash"
	"beego_base_demo/Md5"
	"beego_base_demo/mysqlConn"
	"beego_base_demo/protobuf/AP"
	"beego_base_demo/protobuf/Item"
	"beego_base_demo/protobuf/PB"
	"errors"
	"fmt"
	"github.com/golang/protobuf/proto"
	"github.com/jinzhu/gorm"
	"time"
)

func init() {
	mysqlConn.CreateTable(&Account{})
}
type Account struct {
	ID uint
	Acc string   `gorm:"type:varchar(100);unique"`
	Passwd string   `gorm:"type:varchar(100)"`
	CreatedAt time.Time
}
func (this Account) TableName() string {
	//
	str:=fmt.Sprintf("accounts_copy%d",Hashstr.Hash(this.Acc))
	fmt.Println(str)
	return str
}

func Reset(acc,oldpasswd ,newpasswd string) bool {
	//查看数据库是否有这个数据
	newpasswd=Md5.Encode(newpasswd)

	var account Account
	account.Acc=acc
	err:=mysqlConn.GetInstance().Where(&account).First(&account).Error
	if errors.Is(err, gorm.ErrRecordNotFound){
		return false
	}
	ok:=Md5.Check(oldpasswd,account.Passwd)
	fmt.Println(account.Passwd)
	fmt.Println(oldpasswd)

	if ok {
		//更新密码
		fmt.Println("update 密码")
		err := mysqlConn.GetInstance().Model(&account).Update(Account{Passwd:newpasswd}).Error
		return err == nil
	}
	return ok
}

func Register(acc,passwd string) bool {
	//查看数据库是否有这个数据
	var account Account
	account.Acc=acc
	err:=mysqlConn.GetInstance().Table(account.TableName()).Where(&account).First(&account).Error
	if errors.Is(err, gorm.ErrRecordNotFound){
		var cstZone = time.FixedZone("CST", 8*3600)
		t:=Account{Acc: acc,Passwd: Md5.Encode(passwd),CreatedAt:time.Now().In(cstZone)}
		err=mysqlConn.GetInstance().Create(&t).Error
		fmt.Println(t)
		return err==nil
	}
	return false
}

func Login(request *PB.Packet,response *PB.Packet)  {
	//查看数据库是否有这个数据
	account:=AP.AccPasswd{}
	proto.Unmarshal(request.Marshal_, &account)

	acc:=string(account.Acc)
	out:=&Account{Acc:acc}
	err:=mysqlConn.GetInstance().Where(&Account{Acc:acc}).First(out).Error
	if errors.Is(err, gorm.ErrRecordNotFound){
		return
	}
	ok:=Md5.Check(string(account.Passwd),out.Passwd)
	if ok{
		response.Result=0
	}else{
		response.Result=1
	}
	response.Marshal_, _ =proto.Marshal(&account)
	fmt.Println(response)
	return
}

func AddItem(request *PB.Packet,response *PB.Packet)  {
	//查看数据库是否有这个数据
	items:=Item.Items{}
	err := proto.Unmarshal(request.Marshal_, &items)
	if err != nil {
		return
	}
	items_pairs:=items.GetItemPairs()
	for i:=range items_pairs{

	}

	return
}

